package org.xxpay.pay.channel.sufpay;

import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.xxpay.core.common.constant.PayConstant;
import org.xxpay.core.common.domain.api.AbstractRes;
import org.xxpay.core.common.domain.api.ApiBuilder;
import org.xxpay.core.common.domain.api.PayRes;
import org.xxpay.core.common.domain.api.msg.QueryRetMsg;
import org.xxpay.core.common.util.MyLog;
import org.xxpay.core.common.util.PayDigestUtil;
import org.xxpay.core.common.util.XXPayUtil;
import org.xxpay.core.common.vo.DBApplicationConfig;
import org.xxpay.core.entity.PayOrder;
import org.xxpay.pay.channel.BasePayment;
import org.xxpay.pay.util.Util;

import java.util.Map;
import java.util.TreeMap;

/**
 * @description: 速付支付
 */
@Service
public class SufpayPaymentService extends BasePayment {

    private static final MyLog _log = MyLog.getLog(SufpayPaymentService.class);

    @Override
    public String getChannelName() {
        return SufpayConfig.CHANNEL_NAME;
    }

    /**
     * 支付
     * @param payOrder
     * @return
     */
    @Override
    public AbstractRes pay(PayOrder payOrder) {

        _log.info("处理["+getChannelName()+"]渠道支付业务, payOrderId={}, channelId={}", payOrder.getPayOrderId(), payOrder.getChannelId());
        String channelId = payOrder.getChannelId();
        switch (channelId) {
            case SufpayConfig.CHANNEL_ALIPAY_H5 :
                return doPay(payOrder, "aliwap");
            case SufpayConfig.CHANNEL_ALIPAY_QR :
                return doPay(payOrder, "aliqrcode");
            default:
                return ApiBuilder.bizError("不支持的渠道[channelId="+channelId+"]");
        }
    }

    private AbstractRes doPay(PayOrder payOrder, String pay_type) {

        SufpayConfig sufpayConfig = new SufpayConfig(getPayParam(payOrder));
        PayRes retObj = ApiBuilder.buildSuccess(PayRes.class);
        DBApplicationConfig dbConfig = getDBApplicationConfig();

        Map<String,Object> paramMap = new TreeMap();
        // 接口类型
        paramMap.put("mchId", sufpayConfig.getMchId());
        paramMap.put("pay_type", pay_type); // 支付类型编码
        paramMap.put("mchOrderNo", payOrder.getPayOrderId());
        paramMap.put("amount", payOrder.getAmount() + "");
        paramMap.put("clientIp", StringUtils.isBlank(payOrder.getClientIp()) || "null".equalsIgnoreCase(payOrder.getClientIp()) ? Util.getRandomIp() : payOrder.getClientIp());
        paramMap.put("timeDate", System.currentTimeMillis()/1000);
        paramMap.put("returnUrl", super.getReturnUrl(getChannelName(), dbConfig));
        paramMap.put("notifyUrl", super.getNotifyUrl(getChannelName(), dbConfig));

        // 签名
        String sign = PayDigestUtil.getSign(paramMap, sufpayConfig.getKey()).toLowerCase();
        paramMap.put("sign", sign);

        String reqUrl = sufpayConfig.getReqUrlHost() + "/create/order?" + XXPayUtil.genUrlParams(paramMap);
        String resData = XXPayUtil.call4Post(reqUrl);
        _log.info("请求["+getChannelName()+"]渠道返回结果:{}， reqUrl={}", resData, reqUrl);
        if(StringUtils.isEmpty(resData)){
            return ApiBuilder.bizError("调起通道失败[通道提示：没有响应结果]");
        }

        JSONObject resDataJSON = JSONObject.parseObject(resData);
        String staticStr = resDataJSON.getString("static");
        String msg = resDataJSON.getString("msg");

        if(!"true".equals(staticStr)){
            return ApiBuilder.bizError("调起通道失败[通道提示："+ msg +"]");
        }


        // 请求地址
        JSONObject dataObj = resDataJSON.getJSONObject("data");
        String toPayUrl = dataObj.getString("payurl");

        retObj.setPayJumpUrl(toPayUrl);      // 可以通过该地址跳转到支付中心界面完成支付(URL)
        StringBuffer payForm = new StringBuffer();
        payForm.append("<script>window.location.href = '"+toPayUrl+"';</script>");

        retObj.setPayUrl(payForm.toString());
        retObj.setPayMethod(PayConstant.PAY_METHOD_FORM_JUMP);

        int updateCount = commonService.payOrderService.updateStatus4Ing(payOrder.getPayOrderId(), resDataJSON.getString("payOrderId"));
        _log.info("[{}]更新订单状态为支付中:payOrderId={},result={}", getChannelName(), payOrder.getPayOrderId(), updateCount);

        return retObj;
    }

    /**
     * 查询订单
     * @param payOrder
     * @return
     */
    @Override
    public QueryRetMsg query(PayOrder payOrder) {
        return QueryRetMsg.waiting();  //支付中
    }

}
